//
//  ScreenLockerViewController.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/7/4.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
enum ScreenStyle {
    case ScreenOpen //开启
    case ScreenVerty //验证
}
class ScreenLockerViewController: BaseViewController, AlertDelegate {
    var passwordView:DKSetTradeView?
    var passWord:String = ""
    var style:ScreenStyle?
    var statesLabel:UILabel?
    var errorNumber:Int = 0  //错误次数
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        AppSecurityInfo.default.readDic()
        if AppSecurityInfo.default.passWordDic[AppSecurityInfo.SecurityInfo.screenPassword] != nil {
        passWord = AppSecurityInfo.default.passWordDic[AppSecurityInfo.SecurityInfo.screenPassword]!
        }
        let headImageView = UIImageView()
        headImageView.layer.cornerRadius = 25
        if let urlstr = AppInfo.default.portrait {
            headImageView.sd_setImage(with: URL(string: urlstr), placeholderImage: #imageLiteral(resourceName: "login_icon"))
        }else {
            headImageView.image = #imageLiteral(resourceName: "login_icon")
        }
        headImageView.layer.masksToBounds = true
        self.view.addSubview(headImageView)
        headImageView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(80)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(50)
        }
        
        let statesLabel = BaseLabel(style: .oneStyle)
        statesLabel.text = kText("输入您的解屏密码")
        self.statesLabel = statesLabel
        statesLabel.font = UIFont.systemFont(ofSize: 15)
        self.view.addSubview(statesLabel)
        statesLabel.snp.makeConstraints { (make) in
            make.top.equalTo(headImageView.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
        }
        if style == .ScreenVerty {
            
        let loadBtn = UIButton()
        loadBtn.setTitle(kText("去登录?"), for: UIControlState.normal)
        loadBtn.addTarget(self, action: #selector(loadBtnAction), for: UIControlEvents.touchUpInside)
        loadBtn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text1, for: UIControlState.normal)
        loadBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        self.view.addSubview(loadBtn)
        loadBtn.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(280)
            make.width.equalTo(150)
            make.height.equalTo(50)
            make.centerX.equalToSuperview()
        }
      }
        
        self.creatPassWord()
        
    }
    
    func creatPassWord() {
        passwordView = DKSetTradeView(title: "",cryptograph: false, length: 4,height:200) {[weak self] (text:String) in
            if self?.style == .ScreenVerty {
                if text == self?.passWord {
                    self?.dismiss(animated: true, completion: nil)
                }else {
                    self?.passwordView?.subviews.forEach({ (iteam) in
                        iteam.removeFromSuperview()
                    })
                    self?.passwordView?.removeFromSuperview()
                    self?.errorNumber = (self?.errorNumber)! + 1
                    if self?.errorNumber == 3 {
                        AppInfo.default.isLogin = false
                        self?.dismiss(animated: true, completion: nil)
                        return
                    }
                    CYMBShow.showMessage(kText("密码错误,请重新输入"))
                    self?.statesLabel?.text = String(format: "%d/3", (self?.errorNumber)!)
                    self?.creatPassWord()
                }
                return
            }
            
            self?.passwordView?.subviews.forEach({ (iteam) in
                iteam.removeFromSuperview()
            })
            self?.passwordView?.removeFromSuperview()
            self?.passWord = text
            self?.statesLabel?.text = kText("请再次输入您的解屏密码")
            self?.passwordView = DKSetTradeView(title: "",cryptograph: false, length: 4,height:200) { (infor:String) in
                if self?.passWord == infor {
                    var dic:[String:String] = [:]
                    dic[AppSecurityInfo.SecurityInfo.openScreenKey] = "1"
                    dic[AppSecurityInfo.SecurityInfo.screenPassword] = infor
                    AppSecurityInfo.default.openScreenLock(dic: dic)
                    CYMBShow.showMessage(kText("解屏密码设置成功"))
                    self?.navigationController?.popViewController(animated: true)
                }else {
                    CYMBShow.showMessage(kText("两次密码输入的不一致,请重新设置"))
                    self?.passwordView?.subviews.forEach({ (iteam) in
                        iteam.removeFromSuperview()
                    })
                    self?.passwordView?.removeFromSuperview()
                    self?.passWord = ""
                    self?.statesLabel?.text = kText("输入您的解屏密码")
                    self?.creatPassWord()
                    
                }
                
            }
            self?.openKeyBoard()
            self?.view.addSubview((self?.passwordView)!)
        }
        self.openKeyBoard()
        self.view.addSubview(passwordView!)
    }
    
    func openKeyBoard() {
        let time: TimeInterval = 0.5
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
            self.passwordView?.inputTextField.becomeFirstResponder()
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    @objc func loadBtnAction() {
        let controller = LoginViewController()
        controller.isNeedPop = true
        AppInfo.default.isLogin = false
        CYMBShow.currentController()?.navigationController?.pushViewController(controller, animated: true)
        self.dismiss(animated: false, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
